package com.xhwl.centiotdata.handler.visitor.impl;

import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.xhwl.centiotdata.handler.visitor.VisitorIntegrationFactory;
import com.xhwl.centiotdata.handler.visitor.VisitorIntegrationHandler;
import com.xhwl.centiotdata.pojo.constant.DaHuaConstant;
import com.xhwl.centiotdata.pojo.dto.dahua.IdentityDaHuaDTO;
import com.xhwl.centiotdata.pojo.dto.dahua.UserDaHuaDTO;
import com.xhwl.centiotdata.pojo.dto.dahua.VisitorInfoDaHuaDTO;
import com.xhwl.centiotdata.pojo.dto.visitor.VisitorIntegrationConfigDTO;
import com.xhwl.centiotdata.service.cent.IAccountCentService;
import com.xhwl.centiotdata.service.cent.IAuthAccountCentService;
import com.xhwl.centiotdata.suppliersystem.dahua.GeneralDaHuaHandler;
import com.xhwl.centiotdata.suppliersystem.dahua.VisitorDaHuaHandler;
import com.xhwl.centiotdata.utils.RedisUtils;
import com.xhwl.common.dto.cent.visitor.IntervieweeCreateDTO;
import com.xhwl.common.dto.cent.visitor.VisitorAuthDTO;
import com.xhwl.common.dto.cent.visitor.VisitorInfoDTO;
import com.xhwl.common.dto.cent.visitor.VisitorQrCodeDTO;
import com.xhwl.common.enums.pedestrian.PassMediumEnum;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.common.pojo.cent.auth.AuthAccountMapping;
import com.xhwl.common.pojo.cent.sdata.Account;
import com.xhwl.common.pojo.cent.visitor.Follower;
import com.xhwl.common.query.cent.sdata.AccountQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Author: yanyixiong
 * @Description:
 * @Date: create in 9:28 2022/3/4
 */
@Service
public class VisitorIntegrationDaHuaHandler extends VisitorIntegrationHandler {

    @Autowired
    VisitorDaHuaHandler visitorDaHuaHandler;
    @Autowired
    IAccountCentService accountCentService;
    @Autowired
    IAuthAccountCentService authAccountCentService;
    @Autowired
    RedisUtils redisUtils;

    @Override
    public void afterPropertiesSet() throws Exception {
        VisitorIntegrationFactory.register(5,this);
    }

    public AuthAccountMapping createUser(VisitorIntegrationConfigDTO configDTO, IntervieweeCreateDTO intervieweeCreateDTO) {
        Account account = intervieweeCreateDTO.getAccount();
        AuthAccountMapping authAccountMapping = visitorDaHuaHandler.queryUser(account, configDTO);
        if(Objects.nonNull(authAccountMapping)){
            return authAccountMapping;
        }
        String key = String.format(DaHuaConstant.IDENTITY_KEY,configDTO.getProjectId());
        Integer identityId = (Integer) redisUtils.get(key);
        if(identityId == null){
            List list = visitorDaHuaHandler.queryIdentity(configDTO);
            if(CollectionUtils.isEmpty(list)){
                identityId = Math.toIntExact(visitorDaHuaHandler.createIdentity(configDTO));
            }else {
                JSONObject json = (JSONObject) list.get(0);
                IdentityDaHuaDTO identityDaHuaDTO = json.toJavaObject(IdentityDaHuaDTO.class);;
                identityId = Math.toIntExact(identityDaHuaDTO.getId());
            }
            redisUtils.setWithMinute(key,identityId,DaHuaConstant.IDENTITY_TIME);
        }

        Integer age = account.getAge();
        LocalDateTime localDateTime = LocalDateTime.now();
        if(Objects.nonNull(age)){
            localDateTime = localDateTime.minusYears(age);
        }
        String birthday = localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        UserDaHuaDTO userDaHuaDTO = UserDaHuaDTO.builder().birthday(birthday)
                .code(GeneralDaHuaHandler.generateOpenCode(account.getId(),intervieweeCreateDTO.getProjectId()))
                .deptId(1)
                .name(account.getName())
                .paperNumber(intervieweeCreateDTO.getIdentityNum())
                .paperType("身份证")
                .status("在职")
                .phone(account.getPhone())
                .sex(account.getSex() == null || account.getSex() == 0 ? "女" : "男")
                .personIdentityId(identityId.toString()).build();
        return visitorDaHuaHandler.createUser(configDTO, userDaHuaDTO);
    }



    /**
     * 预约授权
     * @param configDTO
     * @param authDTO
     * @return
     */
    @Override
    public ResultJson createVisitorAuth(VisitorIntegrationConfigDTO configDTO, VisitorAuthDTO authDTO) {

        List<Follower> followerList = authDTO.getFollowerList();
        List<VisitorInfoDaHuaDTO.FollowVisitor> followVisitors = new ArrayList<>();
        if(!CollectionUtils.isEmpty(followerList)){
            followerList.forEach(follower -> {
                VisitorInfoDaHuaDTO.FollowVisitor followVisitor = new VisitorInfoDaHuaDTO.FollowVisitor();
                followVisitor.setFaceFile(getBaseByUrl(follower.getFaceUrl()));
                followVisitor.setV_certificateNumber(follower.getIdentityCard());
                followVisitor.setV_name(follower.getName());
                followVisitor.setV_phone(follower.getPhone());
                followVisitors.add(followVisitor);
            });
        }
        VisitorInfoDaHuaDTO visitorInfoDaHuaDTO = VisitorInfoDaHuaDTO.builder().faceFile(getBaseByUrl(authDTO.getFaceUrl()))
                .v_certificateNumber(authDTO.getIdentityCard())
                .v_name(authDTO.getName())
                .v_phone(authDTO.getPhone())
                .v_dw("访客单位")
                .v_plateNumber(authDTO.getCarNum())
                .v_reason(authDTO.getSubjectMatter())
                .v_personSum(1 + (authDTO.getFollowerList() == null ? 0 : authDTO.getFollowerList().size()))
                .v_timeStr(authDTO.getAuthStartTime())
                .v_lvTimeStr(authDTO.getAuthEndTime())
                .visitorType(0)
                .followVisitors(followVisitors)
                .isv_id(0L)
                .faceFile(getBaseByUrl(authDTO.getFaceUrl()))
                .build();
        List<Integer> passWayList = authDTO.getPassWayList();
        //当访客配置开门方式包括了人脸开门
        if(CollectionUtils.isNotEmpty(passWayList) && passWayList.contains(PassMediumEnum.FACE.getId())){
            return visitorDaHuaHandler.createVisitorAuth(configDTO,visitorInfoDaHuaDTO);
        }else{
            return ResultJson.success();
        }

    }

    @Override
    public ResultJson removeVisitorAuth(VisitorIntegrationConfigDTO configDTO, VisitorInfoDTO infoDTO) {
        return ResultJson.success();
    }

    @Override
    public ResultJson getQrCode(VisitorIntegrationConfigDTO configDTO, VisitorAuthDTO visitorAuthDTO) {
        AuthAccountMapping openAccount = this.getOpenAccount(configDTO, visitorAuthDTO);
        visitorAuthDTO.setIntervieweeOpenCode(openAccount.getOpenCode());
        return visitorDaHuaHandler.getQrCode(configDTO,visitorAuthDTO);
    }

    private AuthAccountMapping getOpenAccount(VisitorIntegrationConfigDTO configDTO, VisitorAuthDTO visitorAuthDTO){
        AuthAccountMapping authAccountMapping = authAccountCentService.query(visitorAuthDTO.getProjectId(),visitorAuthDTO.getIntervieweeId(), visitorAuthDTO.getProductId());
        if (Objects.isNull(authAccountMapping)|| StringUtils.isEmpty(authAccountMapping.getOpenCode())) {
            IntervieweeCreateDTO intervieweeCreateDTO = handleCreateUserDTO(visitorAuthDTO);
            authAccountMapping = this.createUser(configDTO, intervieweeCreateDTO);
            if(Objects.nonNull(authAccountMapping)){
                visitorAuthDTO.setIntervieweeOpenId(authAccountMapping.getOpenId());
                visitorAuthDTO.setIntervieweeOpenCode(authAccountMapping.getOpenCode());
            }
        }
        return authAccountMapping;
    }

    private IntervieweeCreateDTO handleCreateUserDTO(VisitorAuthDTO visitorAuthDTO){
        AccountQuery accountQuery = new AccountQuery();
        Integer intervieweeId = visitorAuthDTO.getIntervieweeId();
        accountQuery.setId(intervieweeId);
        IntervieweeCreateDTO intervieweeCreateDTO = new IntervieweeCreateDTO();
        Account account = accountCentService.getAccount(null,accountQuery);
        intervieweeCreateDTO.setProductId(visitorAuthDTO.getProductId());
        intervieweeCreateDTO.setProjectId(visitorAuthDTO.getProjectId());
        //因为主数据没有身份证 随便生成了 @TODO 从企业通讯录拿
        String identityNum = "43252419950625"+String.format("%04d", intervieweeId);
        intervieweeCreateDTO.setIdentityNum(identityNum);
        intervieweeCreateDTO.setAccount(account);
        return intervieweeCreateDTO;
    }

    public static String getBaseByUrl(String url){
        byte[] bytes = HttpRequest.get(url).execute().bodyBytes();
        String encode = Base64Encoder.encode(bytes);
        System.out.println(encode);
        return "data:image/jpeg;base64,"+encode;
    }


}
